package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService extends LogicService<UserDao, User, Long> {

    public UserService(@Autowired UserDao dao) {
        super(dao);
    }

    public User login(String username, String password) {
        User user = this.dao.findByUsername(username);
        if(user==null){
            return null;
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put("id",user.getId());
        claim.put("username",user.getUsername());
        user.setUser_token(JwtUtils.genToken(claim));
        return user;
    }

    public User register(String username, String password) {
        if (dao.findByUsername(username) != null) {
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return dao.save(user);
    }

}
